package bavaria.hightech.banking.logging;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.logging.FileHandler;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 * class LogHandler implements InvocationHandler
 * @author David
 *
 */
public class LogHandler implements InvocationHandler {
	private Object object;
	private static Logger logger = Logger.getLogger(LogHandler.class.getName());
	final LogManager logManager = LogManager.getLogManager();

	/**
	 * default-constructor
	 * @param object
	 */
	public LogHandler(Object object) {
		this.object = object;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		Object result = method.invoke(this.object, args);
		String paramStr = new String();
		if (args != null) {
			for (int i = 0; i < args.length; i++) {
				if (i == (args.length - 1)) {
					paramStr += args[i];
				} else {
					paramStr += args[i] + ", ";
				}
			}
		} else {
			paramStr = "no parameters";
		}
		logger.info("> invoked: " + method.getName() + ", params: " + paramStr
				+ ", Result: " + result);

		try {
			boolean append = true;
			FileHandler fh = new FileHandler("logfiles/TestLog.log", append);
			// fh.setFormatter(new XMLFormatter());
			fh.setFormatter(new SimpleFormatter());
			logger = Logger.getLogger("iBankLogfile");
			logger.addHandler(fh);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;
	}
}